package commonUtility;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
 * Questa classe sarà utilizzata per la creazione del file xml contenente i dati del client
 * da usurpare.
 * @author alex
 */

public class XmlTransferHandler {

	public void makeXml(int id){
		try {
			SAXBuilder builder = new SAXBuilder();         
			Document doc = builder.build(new File("./slaveTmp/"+id+"_transfer_job.xml"));
			Element rootElement = new Element("GATEWAY");
			doc = new Document(rootElement); 
			XMLOutputter out = new XMLOutputter();
			try {
				out.output(doc, new FileOutputStream("./slaveTmp/"+id+"_transfer_job.xml"));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}         } catch (Exception e) {
				e.printStackTrace();
			}
	}
	public void addClient(int id,String btAddress, String file, String time, String port){		
		String filePath = "./slaveTmp/"+id+"_transfer_job.xml";
		SAXBuilder builder = new SAXBuilder();
		Document document = null;
		try {
			document = builder.build(new File(filePath));
		} catch (JDOMException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} 
		/**
		 * Creo l'elemento figlio relativo al bluetooth Adress passato.
		 */
		Element root = document.getRootElement(); 
		Element btClient = new Element("CLIENT"); 
		btClient.setAttribute("MAC",btAddress); 
		/**
		 * Creo e setto gli attibuti del figlio .
		 */	
		Element source = new Element("SOURCE"); 
		Element timeValue = new Element("TRANSMITTEDTIME"); 
		Element portBt = new Element("PORT");  
		source.setText(file); 
		timeValue.setText(time); 
		portBt.setText(port); 
		btClient.addContent(source); 
		btClient.addContent(timeValue);
		btClient.addContent(portBt);
		root.addContent(btClient);
		/**
		 * Scrivo il file.
		 */
		XMLOutputter outputter = new XMLOutputter(); 
		outputter.setFormat(Format.getPrettyFormat()); 
		try {
			outputter.output(document, new FileOutputStream(filePath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}  	
}
